const express = require('express');
const http = require('http');
const socketIO = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketIO(server);

const PORT = 3000;

// 存储在线用户及其 socket 信息
const users = {};

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
  console.log('a user connected');

  // 用户加入
  socket.on('join', (username) => {
    users[username] = { socketId: socket.id, status: 'available' }; // 添加 status 字段
    socket.username = username;
    io.emit('updateUsers', Object.keys(users));
    console.log(`${username} joined`);
  });

  // 监听来自客户端的信令消息
  socket.on('signal', (data) => {
    // 将信令消息发送给目标用户
    io.to(users[data.to].socketId).emit('signal', {
      signal: data.signal,
      from: socket.username
    });
  });

  // 监听文件传输请求
  socket.on('requestFileTransfer', (data) => {
    const toUser = users[data.to];
    if (toUser && toUser.status === 'available') {
      // 向目标用户发送文件传输请求
      io.to(toUser.socketId).emit('fileTransferRequest', {
        from: socket.username,
        file: data.file
      });
      // 将目标用户状态设置为 'busy'，防止其他用户向其发送请求
      users[data.to].status = 'busy';
      // 将发送者状态设置为 'busy'，防止向其发送请求
      users[socket.username].status = 'busy';
    } else {
      // 目标用户不存在或忙碌，发送错误消息
      socket.emit('fileTransferError', {
        message: 'User is not available or busy.'
      });
    }
  });

  // 监听文件传输响应
  socket.on('respondToTransferRequest', (data) => {
    const fromUser = users[data.from];
    if (fromUser) {
      if (data.response === 'accept') {
        // 目标用户接受了文件传输请求，开始传输
        io.to(fromUser.socketId).emit('transferRequestAccepted', {
          to: socket.username
        });
      } else {
        // 目标用户拒绝了文件传输请求
        io.to(fromUser.socketId).emit('transferRequestRejected', {
          to: socket.username
        });
        // 将发送者状态设置为 'available'
        users[data.from].status = 'available';
      }
    }
    // 无论接受还是拒绝，都将目标用户状态设置为 'available'
    users[socket.username].status = 'available';
  });

  // 监听断开连接
  socket.on('disconnect', () => {
    if (socket.username) {
      delete users[socket.username];
      io.emit('updateUsers', Object.keys(users));
      console.log(`${socket.username} disconnected`);
    }
  });
});

server.listen(PORT, () => {
  console.log(`listening on *:${PORT}`);
}); 